package com.sxpi.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@RestController
@RequestMapping("/image")
public class UploadController {
    private static final String IMAGE_DIRECTORY = "D:/upload/";
    @GetMapping("/{imageName}")
    public ResponseEntity<InputStreamResource> getImage(@PathVariable String imageName) throws IOException {
        // 创建图片文件的路径
        Path imagePath = Paths.get(IMAGE_DIRECTORY + imageName).normalize();
        File file = imagePath.toFile();

        // 如果文件不存在，返回 404 错误
        if (!file.exists()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }

        // 获取文件的 MIME 类型
        String contentType = Files.probeContentType(imagePath);
        if (contentType == null) {
            contentType = "application/octet-stream";  // 默认 MIME 类型
        }

        // 使用 InputStreamResource 将文件内容传输
        InputStreamResource resource = new InputStreamResource(new FileInputStream(file));

        // 返回 ResponseEntity，设置 Content-Type 和响应体
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(contentType))
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + imageName)
                .body(resource);
    }
}
